package com.joint.web.action.com;

import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.fz.us.base.util.LogUtil;
import com.fz.us.dict.service.DictService;
import com.google.common.collect.Sets;
import com.joint.base.bean.FlowEnum;
import com.joint.base.entity.*;
import com.joint.base.exception.users.DutyNotExistsException;
import com.joint.base.exception.workflow.PcfgNotExistException;
import com.joint.base.service.DepartmentService;
import com.joint.base.service.PostService;
import com.joint.base.service.ReadersService;
import com.joint.base.service.UsersService;
import com.joint.base.util.DataUtil;
import com.joint.core.entity.Interview;
import com.joint.core.entity.Manage;
import com.joint.core.service.EmployeesService;
import com.joint.core.service.InterviewService;
import com.joint.core.service.ManageService;
import com.joint.web.action.BaseFlowAction;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.convention.annotation.ParentPackage;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by root on 16/12/16.
 */
@ParentPackage("com")
public class AjaxInterviewAction extends BaseFlowAction {

    @Resource
    private InterviewService interviewService;
    @Resource
    private UsersService usersService;
    @Resource
    private ManageService manageService;
    @Resource
    private DepartmentService departmentService;
    @Resource
    private EmployeesService employeesService;
    @Resource
    private PostService postService;
    @Resource
    private ReadersService readersService;

    private Interview interview;
    private String cardID;
    private String interviewDate;
    private String result;
    private String remark;
    private Users creater;
    private String createDate;
    private Users loginUser;
    private String chargeId;
    private String recordId;
    private String recordText;
    private String recordfileId;
    private ArrayList<Map<String,Object>> typesArrayList;
    private String postId;
    private String postName;
    private String interviewDepartId;
    private String departName;
    private String sex;
    private int ifGot;
    private Post post;

    private String name;
    private String interviewerId;
    private Manage manage;
    private String ifCharge;

    /**
     * 视图类型
     */
    private String viewtype;

    /**
     * 项目视图
     * @return
     */
    public String execute(){
        return "interview";
    }

    public String listfordialog(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
        //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            manage = manageService.get(parentId);
            params.put("manage",manage);
        }
        params.put("company",com);
        params.put("ifGot",1);
        params.put("result","0");
        params.put("state",BaseEnum.StateEnum.Enable);
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=interviewService.findByPagerAndProcessState(pager,user, "interview", FlowEnum.ProcessState.Finished, params);

        List<Interview> mList;
        if (pager.getTotalCount() > 0){
            mList = (List<Interview>) pager.getList();
        }else{
            mList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Interview m:mList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",m.getId());
            rMap.put("name",m.getName());
            rMap.put("cardID",m.getCardID());
            rMap.put("state",m.getProcessState().value());
            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);
        LogUtil.info("dataRows"+dataRows);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    /**
     * 判断是否为面试负责人
     * @return
     */
    public String checkUser(){

        manage = manageService.get(parentId);
        Set<Users> chargeUsers = manage.getChargeUsers();
        loginUser=usersService.getLoginInfo();
        Map<String,String> data=new HashMap<String, String>();
        for (Users users:chargeUsers){
            if(users.equals(loginUser)){
                ifCharge="1";
                data.put("ifCharge",ifCharge);
            }else {
                data.put("ifCharge",ifCharge);

            }

        }

        return  ajaxJson(JSONObject.fromObject(data).toString());
    }


    public String list(){
        pager = new Pager();
        if (rows <= 0){
            rows = 10;
        }
        pager.setPageSize(rows);
        pager.setPageNumber(page);
        pager.setOrderBy("createDate");
        pager.setOrderType(BaseEnum.OrderType.desc);

        if(StringUtils.isNotEmpty(sidx)&& BaseEnum.OrderType.valueOf(sord)!=null){
            pager.setOrderBy(sidx);
            pager.setOrderType(BaseEnum.OrderType.valueOf(sord));
        }
        Company com = usersService.getCompanyByUser();
        Users user = usersService.getLoginInfo();

        Map<String,Object> params = new HashMap<String,Object>();
        params = getSearchFilterParams(_search,params,filters);
         //内嵌视图这里要加上
        if (StringUtils.isNotEmpty(parentId)){
            manage = manageService.get(parentId);
            params.put("manage",manage);
        }
        params.put("company",com);
        params.put("state",BaseEnum.StateEnum.Enable);
        //所有单子
        params.put("processState", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny});
        pager=interviewService.findByPagerAndLimit(true, "interview", pager, params);

        List<Interview> mList;
        if (pager.getTotalCount() > 0){
            mList = (List<Interview>) pager.getList();
        }else{
            mList = new ArrayList<>();
        }

        List<JSONObject> dataRows=new ArrayList<JSONObject>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;

        for(Interview m:mList){
            rMap = new HashMap<String,Object>();
            rMap.put("id",m.getId());
            rMap.put("parentId",parentId);
            rMap.put("name",m.getName());
            rMap.put("cardID",m.getCardID());
            String result = m.getResult();
            if(StringUtils.isNotEmpty(result)) {
                if (result.equals("0")) {
                    rMap.put("result", "推荐录用");
                } else if (result.equals("1")) {
                    rMap.put("result", "进入下一轮");
                } else if (result.equals("2")) {
                    rMap.put("result", "淘汰");
                } else {
                    rMap.put("result", " ");
                }
            }
            rMap.put("year", DataUtil.DateToString(m.getCreateDate(),"yyyy"));
            rMap.put("month", DataUtil.DateToString(m.getCreateDate(),"MM"));
            rMap.put("state",m.getProcessState().value());

            JSONObject o = JSONObject.fromObject(rMap);
            dataRows.add(o);
        }

        data.put("dataRows",dataRows);
        data.put("page",page);
        data.put("rows",rows);

        long recordsNum = pager.getTotalCount();
        data.put("total",calcPageNum(recordsNum));
        data.put("records",recordsNum);
        LogUtil.info("dataRows"+dataRows);
        return  ajaxJson(JSONObject.fromObject(data).toString());
    }

    public String read(){

        recordfileId="";
        loginUser = usersService.getLoginInfo();
        if(StringUtils.isNotEmpty(keyId)) {
            interview = interviewService.get(keyId);
            //interviewer = interview.getInterviewer();

            numStatus = workflowService.getNumStatus(keyId, loginUser);
            if(interview.getRecord().size()>0){
                for(FileManage r:interview.getRecord()){
                    recordfileId+=r.getId()+",";
                }
            }
        }

        return "read";
    }

    public String input(){
        LogUtil.info("parentId"+parentId);

        if(StringUtils.isNotEmpty(parentId)) {
            manage= manageService.get(parentId);
            post=manage.getPost();
        }
        recordfileId="";
        if (StringUtils.isNotEmpty(keyId)){
            interview= interviewService.get(keyId);
            post=interview.getPost();
           // interviewer = interview.getInterviewer();
            if(interview.getRecord().size()>0){
                for(FileManage r:interview.getRecord()){
                    recordfileId+=r.getId()+",";
                }
            }
            createDate= DataUtil.DateToString(interview.getCreateDate(),"yyyy-MM-dd");
            creater=interview.getCreater();

        } else {
            loginUser = usersService.getLoginInfo();
            Company company = usersService.getCompanyByUser();
            creater=loginUser;
            createDate= DataUtil.DateToString(new Date(),"yyyy-MM-dd");

        }

        return "input";
    }

    /**
     * 公共保存方法
     */
    private void setData(){

        Set<Users> usersSet= Sets.newHashSet();
        Set<FileManage> recordFile= Sets.newHashSet();

        if(StringUtils.isNotEmpty(keyId)){
            interview = interviewService.get(keyId);
        }else{
            interview = new Interview();
            interview.setCreater(usersService.getLoginInfo());
        }
        if(StringUtils.isNotEmpty(recordId)){
            for(String r:recordId.split(",")){
                recordFile.add(fileManageService.get(r.trim()));
            }
        }
        if(StringUtils.isNotEmpty(postId)){
            interview.setPost(postService.get(postId));
        }
        if(StringUtils.isNotEmpty(interviewDepartId)){
            interview.setDepartment(departmentService.get(interviewDepartId));
        }
        if(StringUtils.isNotEmpty(interviewerId)){
            for(String id:interviewerId.split(",")){
                usersSet.add(usersService.get(id.trim()));
            }
        }
        if(StringUtils.isNotEmpty(interviewDate)){
            interview.setInterviewDate(DataUtil.StringToDate(interviewDate));
        }
        if(StringUtils.isNotEmpty(parentId)){
            interview.setManage(manageService.get(parentId));
        }

        LogUtil.info("parentId"+parentId);
        LogUtil.info("parentId"+manageService.get(parentId));

        interview.setIfGot(1);
        interview.setInterviewer(usersSet);
        interview.setCardID(cardID);
        interview.setName(name);
        interview.setResult(result);
        interview.setRemark(remark);
        interview.setRecord(recordFile);
        interview.setRecordText(recordText);
        interview.setCompany(usersService.getLoginInfo().getCompany());

    }

    /**
     * 保存
     * @return
     */
    public String save(){
        setData();
        try {
            if(StringUtils.isNotEmpty(keyId)){
                interviewService.update(interview);
            } else {
                Map<String, Object> various = new HashMap<String, Object>();
                various.put("numStatus", 0);
                various.put("initDuty", curDutyId);
                interviewService.save(interview, "interview", various);
            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        return ajaxHtmlCallback("200", "保存成功！", "操作状态");
    }

    /**
     * 提交
     * @return
     */
    public String commit(){
        setData();
        Map<String, Object> var1 = new HashMap<String, Object>();
        var1.put("numStatus", 0);
        var1.put("curDutyId", curDutyId);
        var1.put("initDuty", curDutyId);
        Map<String, Object> var2 = new HashMap<String, Object>();
        var2.put("numStatus", 1);
        var2.put("curDutyId", curDutyId);
        Set<Users> usersSet= Sets.newHashSet();


        try {
            if (StringUtils.isNotEmpty(keyId)) {
                interviewService.approve(interview, FlowEnum.ProcessState.Finished, var2, curDutyId,comment);
            } else {
                keyId=interviewService.commit(interview, FlowEnum.ProcessState.Finished,"interview", var1,var2, curDutyId);

            }
        } catch (DutyNotExistsException e) {
            return ajaxHtmlCallback("404", "当前人员无新建权限，请联系管理员！", "操作状态");
        } catch (PcfgNotExistException e) {
            return ajaxHtmlCallback("404", "找不到流程节点配置，请联系管理员！", "操作状态");
        }

        Set<Users> usersList = interview.getManage().getChargeUsers();
        for(Users users:usersList){
            usersSet.add(users);
            //LogUtil.info("++++"+usersSet);
        }
        //增加归档后读者
        for(Users users:usersSet){
            Readers readers = new Readers();
            readers.setUsers(users);
            readers.setBussinessKey("interview");
            readers.setKeyId(keyId);
            readers.setType(2);
            readersService.save(readers);
        }
        return ajaxHtmlCallback("200", "提交成功！", "操作状态");
    }

    public Interview getInterview() {
        return interview;
    }

    public void setInterview(Interview interview) {
        this.interview = interview;
    }


    public String getCreateDate() {
        return createDate;
    }

    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }

    public Users getCreater() {
        return creater;
    }

    public void setCreater(Users creater) {
        this.creater = creater;
    }

    public String getResult() {
        return result;
    }

    public void setResult(String result) {
        this.result = result;
    }

    public String getRemark() {
        return remark;
    }

    public void setRemark(String remark) {
        this.remark = remark;
    }

    public Users getLoginUser() {
        return loginUser;
    }

    public void setLoginUser(Users loginUser) {
        this.loginUser = loginUser;
    }

    public String getChargeId() {
        return chargeId;
    }

    public void setChargeId(String chargeId) {
        this.chargeId = chargeId;
    }

    public String getRecordId() {
        return recordId;
    }

    public void setRecordId(String recordId) {
        this.recordId = recordId;
    }

    public String getRecordfileId() {
        return recordfileId;
    }

    public void setRecordfileId(String recordfileId) {
        this.recordfileId = recordfileId;
    }

    public String getViewtype() {
        return viewtype;
    }

    public void setViewtype(String viewtype) {
        this.viewtype = viewtype;
    }

    public String getPostId() {
        return postId;
    }

    public void setPostId(String postId) {
        this.postId = postId;
    }

    public String getPostName() {
        return postName;
    }

    public void setPostName(String postName) {
        this.postName = postName;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getInterviewDate() {
        return interviewDate;
    }

    public void setInterviewDate(String interviewDate) {
        this.interviewDate = interviewDate;
    }

    public String getRecordText() {
        return recordText;
    }

    public void setRecordText(String recordText) {
        this.recordText = recordText;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getInterviewerId() {
        return interviewerId;
    }

    public void setInterviewerId(String interviewerId) {
        this.interviewerId = interviewerId;
    }

    public String getCardID() {
        return cardID;
    }

    public void setCardID(String cardID) {
        this.cardID = cardID;
    }

    public ArrayList<Map<String, Object>> getTypesArrayList() {
        return typesArrayList;
    }

    public void setTypesArrayList(ArrayList<Map<String, Object>> typesArrayList) {
        this.typesArrayList = typesArrayList;
    }

    public Manage getManage() {
        return manage;
    }

    public void setManage(Manage manage) {
        this.manage = manage;
    }

    public String getIfCharge() {
        return ifCharge;
    }

    public void setIfCharge(String ifCharge) {
        this.ifCharge = ifCharge;
    }

    public int getIfGot() {
        return ifGot;
    }

    public void setIfGot(int ifGot) {
        this.ifGot = ifGot;
    }

    /*public Set<Users> getInterviewer() {
        return interviewer;
    }

    public void setInterviewer(Set<Users> interviewer) {
        this.interviewer = interviewer;
    }*/

    public String getDepartName() {
        return departName;
    }

    public void setDepartName(String departName) {
        this.departName = departName;
    }

    public Post getPost() {
        return post;
    }

    public void setPost(Post post) {
        this.post = post;
    }


    public String getInterviewDepartId() {
        return interviewDepartId;
    }

    public void setInterviewDepartId(String interviewDepartId) {
        this.interviewDepartId = interviewDepartId;
    }
}
